/* 
 * @(#)SendMessageClient.java    Created on 2012-6-29
 * Copyright (c) 2012 ZDSoft Networks, Inc. All rights reserved.
 * $Id$
 */
package bjxg.test.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * @author chengcy
 * @version $Revision: 1.0 $, $Date: 2012-6-29 上午10:37:41 $
 */
public class SendMessageClient {
    private String url;
    private String requestMethod = "POST";
    private String responseContent;
    private String requestContent;
    private String contentType = "text/plain";
    private HttpURLConnection conn = null;
    private static final Logger log = Logger.getLogger(SendMessageClient.class);

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public void setRequestMethod(String requestMethod) {
        this.requestMethod = requestMethod;
    }

    /*
     * 发送方法 @return Returns 是否发送成功
     */
    public boolean send() {
        String sendData = this.requestContent;
        boolean isSuccess = false;
        try {
            URL url = new URL(this.url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod(this.requestMethod);
            conn.setUseCaches(false);
            // conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Content-Length", String.valueOf(sendData.length()));
            conn.setDoInput(true);
            conn.connect();
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(sendData);
            out.flush();
            out.close();

            int code = conn.getResponseCode();
            if (code != 200) {
                String message = "Connect Server error: HTTP Status " + code + " - " + this.url;
                log.debug(message);
            }
            else {
                isSuccess = true;
                BufferedReader in = null;
                StringBuffer sb = new StringBuffer();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    sb.append(inputLine);
                    sb.append("\n");
                }
                this.responseContent = sb.toString();
            }
        }
        catch (ConnectException e) {
            log.error("Connection refused: " + this.url);
            log.debug("连接失败:", e);
        }
        catch (Exception e) {
            log.error("发送数据时出现错误");
            if (log.isDebugEnabled()) {
                log.debug(this.requestContent, e);
            }
        }
        finally {
            conn.disconnect();
        }
        return isSuccess;
    }

    /*
     * 设置URL
     */
    public void setUrl(String url) {
        if (url.matches("^[a-zA-z]+://(.)*")) {
            this.url = url;
        }
        else {
            log.error("服务器地址不正确");
            System.exit(0);
        }
    }

    /*
     * 设置要发送的数据
     */
    public void setRequestContent(String requestContent) {
        this.requestContent = requestContent;
    }

    /*
     * 得到返回的数据
     */
    public String getResponseContent() {
        return this.responseContent;
    }

}
